﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web.Script.Serialization;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Forms;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Drawing;
using System.Data;
using System.Security;
using NAudio.CoreAudioApi;
using System.IO;

namespace 盎宇宙服务
{

    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window

    {
        //[DllImport("user32.dll")]
         [DllImport("user32")]
        public static extern void mouse_event(uint dwFlags, uint dx, uint dy, uint dwData, int dwExtraInfo);

        public const uint MOUSEEVENTF_LEFTDOWN = 0x0002;
        public const uint MOUSEEVENTF_LEFTUP = 0x0004;
        public const uint MOUSEEVENTF_MOVE = 0x0001;

        public const uint WM_SYSCOMMAND = 0x0112;
        public const uint SC_MONITORPOWER =0xF170;
        private static readonly IntPtr HWND_BROADCAST = new IntPtr(0xffff);

        const int APPCOMMAND_VOLUME_MUTE = 0x80000;
        const int APPCOMMAND_VOLUME_UP = 0xA0000;
        const int APPCOMMAND_VOLUME_DOWN = 0x90000;
        const int WM_APPCOMMAND = 0x319;



        static IntPtr HWND_TOPMOST = new IntPtr(-1);
        const uint SWP_NOSIZE = 0x0001;
        const uint SWP_NOMOVE = 0x0002;
        const uint SWP_SHOWWINDOW = 0x0040;
        [DllImport("user32")]
        public static extern IntPtr SendMessage(IntPtr hWnd, uint wMsg, uint wParam, int lParam);
        public static void MoveAndClick(int x, int y)
        {
            SetCursorPos(x, y); // 移动鼠标到指定坐标
            mouse_event(MOUSEEVENTF_LEFTDOWN, (uint)x, (uint)y, 0, 0); // 模拟左键按下
            mouse_event(MOUSEEVENTF_LEFTUP, (uint)x, (uint)y, 0, 0); // 模拟左键释放
        }

        [DllImport("user32.dll")]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern bool SetCursorPos(int x, int y);

        [DllImport("user32.dll")]
        public static extern IntPtr SendMessageW(IntPtr hWnd, int Msg, IntPtr wParam, IntPtr lParam);

        int CommandPort { get; set; } = 14001;
        int CommandPort14000 { get; set; } = 14000;
        QRWindows QRWin =QRWindows.GetInstance1();
        QRWindows QRWin2 = QRWindows.GetInstance2();
        private static int Monitor = 0;
        private static int KTVmove = 0;
        const int MONITOR_OFF = 2;
        const int MONITOR_ON = -1;

        public static UdpClient clientCommand { get; set; } //= new UdpClient(new IPEndPoint(IPAddress.Any, 14000));
        public static UdpClient clientCommand14000 { get; set; } //= new UdpClient(new IPEndPoint(IPAddress.Any, 14000));
        public MainWindow()
        {
            InitializeComponent();
            try
            {
                if (App.IsPortOccupedFun1(CommandPort))
                {
                    System.Windows.Forms.MessageBox.Show("端口" + CommandPort.ToString() + "被占用，可视对讲功能不可用,可重启电脑尝试恢复");
                    //  Process.GetCurrentProcess().Kill();
                    //   return;
                }
                else
                {
                    clientCommand = new UdpClient(new IPEndPoint(IPAddress.Any, CommandPort));
                }
                if (App.IsPortOccupedFun1(CommandPort14000))
                {
                    System.Windows.Forms.MessageBox.Show("端口" + CommandPort14000.ToString() + "被占用，可视对讲功能不可用,可重启电脑尝试恢复");
                    //  Process.GetCurrentProcess().Kill();
                    //   return;
                }
                else
                {
                    clientCommand14000 = new UdpClient(new IPEndPoint(IPAddress.Any, CommandPort14000));
                }
                Thread thread = new Thread(new ThreadStart(ReciveCommandMessage));
                thread.IsBackground = true;
                thread.Start();
                new AutoStartServer().SetMeAutoStart(true);
                var i = SystemTray.Instance;
                this.Visibility = Visibility.Hidden;
              //  ConsoleManager.Show();
                //QRWin.ShowQRwindows1(0, 0);
                //QRWin2.ShowQRwindows2(0, 0);
            }
            catch (Exception ex)
            {
                System.Windows.MessageBox.Show(ex.Message);
            }

        }
        private static IntPtr FindWindowByTitle(string title)
        {
            IntPtr handle = IntPtr.Zero;
            var igs= Process.GetProcessesByName(title);
            foreach (Process process in igs)
            {
                if (!string.IsNullOrWhiteSpace(process.MainWindowTitle)&&process.MainWindowHandle!=IntPtr.Zero )
                {
                    handle = process.MainWindowHandle;
                    break;
                }
            }

            return handle;
        }
        //[System.Runtime.ExceptionServices.HandleProcessCorruptedStateExceptions]
        private void ReciveCommandMessage()
        {
            // public const uint WM_SYSCOMMAND = 0x0112;
            // public const uint SC_MONITORPOWER =0xF170;
            // private static readonly IntPtr HWND_BROADCAST = new IntPtr(0xffff);
            // public static extern IntPtr SendMessage(IntPtr hWnd, uint wMsg, uint wParam, int lParam);
            
    
            while (true)
            {
                try
                {
                    //   QRWindows QRWin = new QRWindows();                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               
                    IPEndPoint ipendpoint = null;
                    if (clientCommand == null)
                        break;
                    byte[] bytea = clientCommand.Receive(ref ipendpoint); //停在这等待数据

                    if (bytea == null) continue;

                    string command = System.Text.Encoding.UTF8.GetString(bytea);

                    if (string.IsNullOrWhiteSpace(command)) continue;

                    JavaScriptSerializer js = new JavaScriptSerializer();
                    // 创建MMDeviceEnumerator对象
               
                    //string processPath = "K:\\Kge/ig8.exe";
                    //   Process KTVProcess = new Process();
                    //   KTVProcess.StartInfo.FileName = processPath;

                    // QRWin.Show();
                    var cmd = js.Deserialize<CmdResult>(command);
                    if (cmd.cmd.Equals("shutdownPC"))
                    {
                        CmdResult cmdResult = new CmdResult();
                        cmdResult.cmd = "Replyshutdown";
                        cmdResult.ID = cmd.ID;
                        cmdResult.result = "ok";
                        var send = System.Text.Encoding.UTF8.GetBytes(js.Serialize(cmdResult));
                        clientCommand.Send(send, send.Length, ipendpoint);
                        // Thread.Sleep(1000);
                        Process.Start("Shutdown.exe", " -s -t 0");
                    }
                    else if (cmd.cmd.Equals("CloseMonitor"))
                    {
                        if (Monitor != MONITOR_OFF)
                        {
                            Monitor = MONITOR_OFF;
                            AdjustVolumeBy(0);
                            Process.Start("D:\\sleep/sleep.exe");
                            CmdResult cmdResult = new CmdResult();
                            cmdResult.cmd = "RestCloseMonitor";
                            cmdResult.ID = cmd.ID;
                            cmdResult.result = "ok";
                            var send = System.Text.Encoding.UTF8.GetBytes(js.Serialize(cmdResult));
                            clientCommand.Send(send, send.Length, ipendpoint);
                            //  defaultDevice = deviceEnumerator.GetDefaultAudioEndpoint(DataFlow.Render, Role.Multimedia);
                            //  defaultDevice.AudioEndpointVolume.MasterVolumeLevelScalar = 0 / 100.0F;


                            // Thread.Sleep(1000);
                            //   Process.Start("Shutdown.exe", " -s -t 0");
                            //  SendMessage(HWND_BROADCAST, WM_SYSCOMMAND, SC_MONITORPOWER, 2);
                        }
                    }
                    else if (cmd.cmd.Equals("OpenMonitor"))
                    {
                        if (Monitor == MONITOR_OFF)
                        {
                            Monitor = MONITOR_ON;
                            SendKeys.SendWait("ENTER");
                            Thread.Sleep(500);
                            SendKeys.SendWait("^{ESC}");
                            Thread.Sleep(100);
                            SendKeys.SendWait("^{ESC}");
                            AdjustVolumeBy(37);
                            CmdResult cmdResult = new CmdResult();
                            cmdResult.cmd = "RestOpenMonitor";
                            cmdResult.ID = cmd.ID;
                            cmdResult.result = "ok";
                            var send = System.Text.Encoding.UTF8.GetBytes(js.Serialize(cmdResult));
                            clientCommand.Send(send, send.Length, ipendpoint);
                        }
                        
                    }
                    else if (cmd.cmd.Equals("OpenKTV"))
                    {
                        CmdResult cmdResult = new CmdResult();
                        cmdResult.cmd = "AckForOpenKTV";
                        cmdResult.ID = cmd.ID;
                        cmdResult.result = "ok";
                        var send = System.Text.Encoding.UTF8.GetBytes(js.Serialize(cmdResult));
                        clientCommand.Send(send, send.Length, ipendpoint);
                        //  Process.Start("D:\\Kge\\igeba/ig8.exe");
                        CloseIg8();
                      
                        string exePath = "D:\\Kge\\igeba/ig8.exe";
                 

                        // 创建一个ProcessStartInfo对象来配置启动选项A
                        ProcessStartInfo startInfo = new ProcessStartInfo(exePath);
                        Process process = new Process();
                        process.StartInfo = startInfo;
                        process.Start();
                        System.Threading.Thread.Sleep(2000);

                        // 将窗口设置为最顶层
                        var setwindowos= NativeMethods.SetWindowPos(process.Handle, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE | SWP_SHOWWINDOW);

                        // 显示窗口
                        var showmain = NativeMethods.ShowWindow(process.Handle, 0);
                        // 使用Win32 API来将窗口置顶
                        var ce1 = NativeMethods.SetForegroundWindow(process.Handle);

                        // 恢复窗口的 Z 顺序（如果需要）
                        // SetWindowPos(process.Handle, HWND_NOTOPMOST, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE | SWP_SHOWWINDOW);

                        Console.WriteLine("0：" + showmain.ToString() + ce1.ToString());


                      
                        // 将进程的窗口置顶
                        // if (!process.HasExited)
                        // {
                        //     IntPtr hWnd = process.MainWindowHandle;
                        //     if (hWnd != IntPtr.Zero)
                        //     { // 将窗口移到屏幕的顶部并显示窗口
                        //         NativeMethods.SetWindowPos(hWnd, IntPtr.Zero, 0, 0, 0, 0, NativeMethods.SWP_SHOWWINDOW);
                        //
                        //         // 使用Win32 API来将窗口置顶
                        //         NativeMethods.SetForegroundWindow(hWnd);A
                        //     }
                        // }

                        Thread.Sleep(5000);
                        SendKeys.SendWait("+a");
                        Thread.Sleep(5000);
                        //MoveAndClick(4140,1100);


                    }else if (cmd.cmd.Equals("RequestKTVQrCode"))
                    {
                        QRCmdResult cmdResult = new QRCmdResult();
                        cmdResult.cmd = "AckForRKQ";
                        cmdResult.ID = cmd.ID;
                        cmdResult.result = "ok";
                        cmdResult.qrCode = "";
                        string qrPath = @"d:\qr.png";
                        if (File.Exists(qrPath))
                            cmdResult.qrCode = QRCodeUtil.DecodeQrCodeByPath(qrPath);
                        else
                        {
                            cmdResult.result = qrPath + "不存在图片";
                        }
                        var send = System.Text.Encoding.UTF8.GetBytes(js.Serialize(cmdResult));
                        clientCommand.Send(send, send.Length, ipendpoint);
                        clientCommand14000.Send(send, send.Length, ipendpoint);
                    }
                    else if (cmd.cmd.Equals("CloseKTV"))
                    {
                        // 指定要关闭的进程名称（不带扩展名）
                        string processName = "ig8"; // 替换为您要关闭的进程名称
                        KTVmove = 0;
                        // 查找匹配的进程
                        Process[] processes = Process.GetProcessesByName(processName);

                        if (processes.Length > 0)
                        {
                            // 关闭所有匹配的进程
                            foreach (Process process in processes)
                            {
                                try
                                {
                                    process.CloseMainWindow(); // 尝试发送关闭窗口消息
                                    if (!process.WaitForExit(5000))
                                    {
                                        // 如果关闭窗口消息无效，强制终止进程
                                        process.Kill();
                                    }
                                    //Console.WriteLine($"已关闭进程：{process.ProcessName}, 进程ID：{process.Id}");
                                    CmdResult cmdResult = new CmdResult();
                                    cmdResult.cmd = "AckForCloseKTV";
                                    cmdResult.ID = cmd.ID;
                                    cmdResult.result = "ok";
                                    var send = System.Text.Encoding.UTF8.GetBytes(js.Serialize(cmdResult));
                                    clientCommand.Send(send, send.Length, ipendpoint);
                                }
                                catch (Exception ex)
                                {
                                    //   Console.WriteLine($"无法关闭进程：{process.ProcessName}, 错误：{ex.Message}");
                                    CmdResult cmdResult = new CmdResult();
                                    cmdResult.cmd = "AckForCloseKTV";
                                    cmdResult.ID = cmd.ID;
                                    cmdResult.result = "NOT";
                                    var send = System.Text.Encoding.UTF8.GetBytes(js.Serialize(cmdResult));
                                    clientCommand.Send(send, send.Length, ipendpoint);
                                }
                            }
                        }
                        else
                        {
                            //   Console.WriteLine("未找到匹配的进程：" + processName);
                            CmdResult cmdResult = new CmdResult();
                            cmdResult.cmd = "AckForCloseKTV";
                            cmdResult.ID = cmd.ID;
                            cmdResult.result = "NOT FIND";
                            var send = System.Text.Encoding.UTF8.GetBytes(js.Serialize(cmdResult));
                            clientCommand.Send(send, send.Length, ipendpoint);
                        }


                    }
                    else if (cmd.cmd.Equals("ShowKTVQrCode"))
                    {
                        if (KTVmove == 0)
                        {
                            MoveAndClick(4140, 1100);
                            KTVmove = 1;
                        }
                        Thread.Sleep(1000);
                        CmdResult cmdResult = new CmdResult();
                        cmdResult.cmd = "AckForSKQ";
                        cmdResult.ID = cmd.ID;
                        cmdResult.result = "ok";
                        var send = System.Text.Encoding.UTF8.GetBytes(js.Serialize(cmdResult));
                        clientCommand.Send(send, send.Length, ipendpoint);
                        // Thread.Sleep(1000);
                        App.Current.Dispatcher.Invoke(() =>
                        {
                            if (!QRWin.IsActive)
                            {
                                QRWin.ShowQRwindows1(2840, 500);
                                QRWin2.ShowQRwindows2(6760, 500);
                            }
                        });

                    }
                    else if (cmd.cmd.Equals("HideKTVQrCode"))
                    {
                        CmdResult cmdResult = new CmdResult();
                        cmdResult.cmd = "AckForHKQ";
                        cmdResult.ID = cmd.ID;
                        cmdResult.result = "ok";
                        var send = System.Text.Encoding.UTF8.GetBytes(js.Serialize(cmdResult));
                        clientCommand.Send(send, send.Length, ipendpoint);
                        // Thread.Sleep(1000);
                        App.Current.Dispatcher.Invoke(() =>
                        {
                              QRWin.HideQRwindows1();
                              QRWin2.HideQRwindows2();
                        });
                    }
                }
                catch(Exception ex)
                {
                    string mes = ex.Message;
                }
            }
        }
        private void CloseIg8()
        {
            // 指定要关闭的进程名称（不带扩展名）
            string processName = "ig8"; // 替换为您要关闭的进程名称
            KTVmove = 0;
            // 查找匹配的进程
            Process[] processes = Process.GetProcessesByName(processName);

            if (processes.Length > 0)
            {
                // 关闭所有匹配的进程
                foreach (Process process in processes)
                {
                    try
                    {
                        process.CloseMainWindow(); // 尝试发送关闭窗口消息
                    }catch(Exception ex)
                    {
                        Console.WriteLine("关闭ig8失败："+ex.Message);
                    }
                }
                Thread.Sleep(2000);
            }
        }
        private void GetCurrentSpeakerVolume(int volume)

        {

            var enumerator = new MMDeviceEnumerator();

            IEnumerable<MMDevice> speakDevices = enumerator.EnumerateAudioEndPoints(DataFlow.Render, DeviceState.Active).ToArray();

            if (speakDevices.Count() > 0)

            {



                MMDevice mMDevice = speakDevices.ToList()[0];

                mMDevice.AudioEndpointVolume.MasterVolumeLevelScalar = volume / 100.0f;

            }
            

        }
        private static void AdjustVolumeBy(int increment)
        {
            MMDeviceEnumerator deviceEnumerator = new MMDeviceEnumerator();
            MMDevice defaultDevice = deviceEnumerator.GetDefaultAudioEndpoint(DataFlow.Render, Role.Multimedia);

            // 获取当前音量
            //float currentVolume = defaultDevice.AudioEndpointVolume.MasterVolumeLevelScalar;

            float value = increment / 100f;
            if (value < 0)
                value = 0f;
            if (value > 1)
                value = 1f;
            // 计算新的音量值
            float newVolume = value; //Math.Min(Math.Max(increment / 100f, 0f), 1f);

            // 设置新的音量
            defaultDevice.AudioEndpointVolume.MasterVolumeLevelScalar = newVolume;

            Console.WriteLine("Volume adjusted. New volume: " + newVolume);
        }
    }

    public class NativeMethods
    {
        [DllImport("user32.dll")]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int x, int y, int cx, int cy, uint uFlags);

        [System.Runtime.InteropServices.DllImport("user32.dll")]
        public static extern bool SetForegroundWindow(IntPtr hWnd);

        [DllImport("user32.dll")]
        public static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);

        
    }
}
